package cn.zhaoyuening.algorithms.stack;

import java.util.Stack;

/**
 * Created by Buynow on 2017/8/6.
 */
public class MinStack<T extends Comparable> extends Stack<T> {
    private Stack<T> dataStack = new Stack<>();
    private Stack<T> minStack = new Stack<>();

    @Override
    public T push(T item) {
        if (minStack.isEmpty()) {
            minStack.push(item);
        }else{
            if (item.compareTo(getMin()) <= 0) {
                minStack.push(item);
            }
        }
        dataStack.push(item);
        return item;
    }

    @Override
    public synchronized T pop() {
        T t = dataStack.pop();
        if (!minStack.isEmpty()) {
            if (t.compareTo(getMin()) == 0) {
                minStack.pop();
            }
        }
        return t;
    }

    public T getMin() {
        return minStack.peek();
    }

    public static void main(String[] args) {
        MinStack<Integer> stack = new MinStack<>();
        stack.push(43);
        stack.push(23);
        stack.push(143);
        stack.push(93);
        stack.push(-3);

        System.out.println(stack.getMin());
        stack.pop();
        System.out.println(stack.getMin());
    }
}
